package phoenics.apeak.bus.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ResolvableType;
import org.springframework.data.redis.core.StringRedisTemplate;

import phoenics.apeak.bus.util.FastSerializationUtils;

public class RedisBaseDao<T> {
	@Autowired
	private StringRedisTemplate  redisTemplate;
	/*test*/
	
	 public void pushObject(final String key,final T member) {  
		 //return 
			redisTemplate.execute(connection->{
			 connection.rPush(takeKey(key), takeValue(member));  
			 return true;
			  //return connection.rPush(takeKey(key), takeValue(member));  
		 });
	 }
	 public T popObject(final String key) {  
		 return  redisTemplate.execute(connection->{
			 return takeValue( connection.lPop(takeKey(key)));
		 });
	 }
	 
	 
	 /////////////////////////////////////////
	 private byte[] takeKey(String keyString){
		 return  redisTemplate.getStringSerializer().serialize(keyString);  
	 }

	 private byte[] takeValue(T t){
		 return  FastSerializationUtils.serialize(t);
	 }
	 private T takeValue(byte[] ts){
		 return  FastSerializationUtils.unserialize(ts, getEntityClass());
	 }
	 @SuppressWarnings("unchecked")
		private  Class<T> getEntityClass(){
			ResolvableType resolvableType1 = ResolvableType.forClass(this.getClass());  
			return (Class<T>) resolvableType1.getSuperType().getGeneric(0).resolve();
		}
	
	

}
